import { Enum } from './enum';

const oneMin = 60;
const oneHour = oneMin * 60;
const oneDay = oneHour * 24;
export const BaseTimeEnum = Enum({
  second: {
    label: '秒',
    value: 1
  },
  min: {
    label: '分',
    value: 60
  },
  hour: {
    label: '时',
    value: oneHour
  },
  day: {
    label: '天',
    value: oneDay
  }
});
const fixPrecision = (value = 0, precision: number) => {
  const precisionStr = `${value}`.split('.').pop() ?? '';
  if (precisionStr.length <= precision) {
    return Number(value);
  }
  return Number(value.toFixed(precision));
};
export const formateDate = (step: number | null, precision = 4) => {
  if (step === null) {
    return {
      value: 0,
      type: BaseTimeEnum.enum.second,
      unit: BaseTimeEnum.getLabelByValue(BaseTimeEnum.enum.second)
    };
  }
  if (step >= oneDay) {
    return {
      value: fixPrecision(step / oneDay, precision),
      type: BaseTimeEnum.enum.day,
      unit: BaseTimeEnum.getLabelByValue(BaseTimeEnum.enum.day)
    };
  }
  if (step >= oneMin && step < oneHour) {
    return {
      value: fixPrecision(step / oneMin, precision),
      type: BaseTimeEnum.enum.min,
      unit: BaseTimeEnum.getLabelByValue(BaseTimeEnum.enum.min)
    };
  }
  if (step >= oneHour && step < oneDay) {
    return {
      value: fixPrecision(step / oneHour, precision),
      type: BaseTimeEnum.enum.hour,
      unit: BaseTimeEnum.getLabelByValue(BaseTimeEnum.enum.hour)
    };
  }
  return {
    value: fixPrecision(step, precision),
    type: BaseTimeEnum.enum.second,
    unit: BaseTimeEnum.getLabelByValue(BaseTimeEnum.enum.second)
  };
};
